<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

class Default_My_Model extends CI_Model
{
    private $_table = "";
    protected $log_event = '';
    protected $log_data = '';
    protected $db_recon = null;
    protected $db_recon_buff = null;

    function __construct()
    {
        parent::__construct();
        $this->load->database();
        
        if ('' == $this->_table)
        {
            $this->set_table();
        }
    }

    public function controllerActionName($isSlas = true)
    {
        if ($isSlas)
        {
            return $classThis = $this->router->class . '/' . $this->router->method;
        }
        else
        {
            return $classThis = $this->router->class . '_' . $this->router->method;
        }
    }

    public function set_table($_tablename = "")
    {
        if (false !== strpos($_tablename, 'seLect'))
        {
            $this->grepTableName($_tablename);
        }
        elseif ('' == $_tablename)
        {
            $this->_table = get_Class($this);
        }
        else
        {
            $this->_table = $_tablename;
        }
    }

    public function grepTableName($_tablename)
    {
        $matches = array();
        
        $int = preg_match_all('/(?<=from).\S+/i', $_tablename, $matches);
        
        if (1 == $int)
        {
            return trim($matches[0][0]);
        }
        else
        {
            return 0;
        }
    }
    
    function search($conditions = NULL, $_tablename = "", $limit = 500, $offset = 0)
    {
        if (!is_array($conditions) and false !== stripos($conditions, 'seLect'))
        {
            $query = $this->db->query($conditions);
        }
        else
        {
            if ($_tablename == "")
            {
                $_tablename = $this->_table;
            }

            if ($conditions != NULL)
            {
                $this->db->where($conditions);
            }
                
            $query = $this->db->get($_tablename, $limit, $offset = 0);
        }

        $_SESSION[USER_AUTH . 'last_query'] = $this->db->last_query();
        
        return $query;
    }

    function searchPaging($tableOrQuery = "", $conditions = NULL, $offset = 0, $limit = PAGES_LIMIT, $nextPage = 0, $pagePerCols = 10, $colPage = 0)
    {
        $data = array();
        
        if (!is_array($tableOrQuery) and false !== stripos($tableOrQuery, 'seLect'))
        {
            $query = $this->db->query($tableOrQuery . ' LIMIT ' . $limit . ' OFFSET ' . $offset);
            $this->set_table($this->grepTableName($tableOrQuery));
            
        }
        else
        {
            if ($tableOrQuery == "")
            {
                $tableOrQuery = $this->_table;
            }

            if ($conditions != NULL)
            {
                $this->db->where($conditions);
            }
                
            $query = $this->db->get($tableOrQuery, $limit, $offset);
            $this->set_table($this->grepTableName($tableOrQuery));
        }
        $query_page = $this->db->query($tableOrQuery );

        $data['data'] = $query->result();
        $data['rows'] = $query->num_rows();
        $data['page'] = $query_page->num_rows();
        $data['numbering'] = $offset;

        $_SESSION[USER_AUTH . 'last_query_' . $this->controllerActionName(false)] = $this->db->last_query();
        $data['paging'] = $this->createPage($data['page'], $offset, $limit, $nextPage, $pagePerCols, $colPage);
        return $data;
    }
    

    function searchNonPaging($conditions = NULL, $_tablename = "")
    {
        $data = array();
        
        if (!is_array($conditions) and false !== stripos($conditions, 'seLect'))
        {
            $query = $this->db->query($conditions);
        }
        else
        {
            if ($_tablename == "")
            {
                $_tablename = $this->_table;
            }

            if ($conditions != NULL)
            {
                $this->db->where($conditions);
            }
                
            $query = $this->db->get($_tablename);
        }
        
        $data['data'] = $query->result();
        $data['rows'] = $query->num_rows();

        $_SESSION[USER_AUTH . 'last_query_' . $this->controllerActionName(false)] = $this->db->last_query();
        
        return $data;
    }

    function insert($data, $_tablename = "")
    {
        if ($_tablename == "")
        {
            $_tablename = $this->_table;
        }

        $this->db->insert($_tablename, $data);
        
        //$this->insertAuditTrail($data);
        
        return $this->db->affected_rows();
    }

    function update($data, $conditions, $_tablename = "")
    {
        if ($_tablename == "")
        {
            $_tablename = $this->_table;
        }

        $this->db->where($conditions);
        $this->db->update($_tablename, $data);
        
        //$this->insertAuditTrail($data);
        
        return $this->db->affected_rows();
    }

    function delete($data, $conditions, $table_name = "")
    {
        if ($table_name == "")
        {
            $table_name = $this->_table;
        }
        
        $this->db->where($conditions);
        $this->db->delete($table_name);
        
        //$this->insertAuditTrail($data);
        
        return $this->db->affected_rows();
    }

    public function reltuples_num_rows($table_name = '')
    {
        if ($table_name == "")
        {
            $this->set_table($table_name);
            $table_name = $this->_table;
        }

        $resultSet = $this->db->query("select reltuples::integer  from pg_class where relname='$table_name'");
        $result = $resultSet->result();

        return $result[0]->reltuples;
    }

    function insertAuditTrail($data)
    {
        $this->setLogData($data);

        if ('' == $this->log_event)
        {
            $this->log_event = $this->controllerActionName(false);
        }

        $params = array(
            'log_time'  => date("Y-m-d H:i:s"),
            'log_aktor' => $this->getUserID(),
            'log_event' => $this->log_event,
            'log_data'  => $this->log_data
        );
        
        $CI = &get_instance();
        
        $db_master = $CI->load->database("default", true);
        
        $db_master->insert('audit_trail', $params);
        
        $flag = $db_master->affected_rows();
        
        $db_master->close();
        
        return $flag;
    }

    public function setLogEvent($logEvent)
    {
        $this->log_event = $logEvent;
    }

    public function setLogData()
    {
        $trace = debug_backtrace();
        $process = '';
        $caller = array_shift($trace);
        $caller = array_shift($trace);
        $process .= $caller['function'] . '/';
        $caller = array_shift($trace);
        $process = $caller['function'] . '/' . $process;
        $log_data = $this->controllerActionName() . '/' . $process;

        $arg_list = func_get_args();
        $log_data .= ":" . json_encode($arg_list);
        
        $this->log_data = $log_data;
    }

    function getUserID()
    {
        if(isset($_SESSION[USER_AUTH . 'user_id']))
        {
            return $_SESSION[USER_AUTH . 'user_id'];
        }
        else
        {
            return "";
        }
    }

    function createPage($jumlah, $offset, $limit, $nextPage, $pagePerCols, $colPage)
    {
        $var = $_GET["v"];

        $addLink = "";

        $arr_pg = array("os", "np", "cp");
        $temp_g = $_GET;
        
        if (is_array($arr_pg))
        {
            foreach ($arr_pg as $key)
            {
                if (isset($temp_g[$key]))
                {
                    unset($temp_g[$key]);
                }
            }
        }

        $arr = array();
        
        foreach ($temp_g as $key2 => $element)
        {
            if (is_array($element))
            {
                foreach ($element as $key3 => $element3)
                {
                    $arr[] = $key2 . '[' . $key3 . ']=' . $element3;
                }
            }
            else
            {
                $arr[] = $key2 . '=' . $element;
            }
        }
        
        if (is_array($arr))
        {
            $addLink = "&" . implode('&', $arr);
        }
        else
        {
            $addLink = "";
        }

        $hasil = "";
        
        if ($jumlah > 0)
        {
            $jumPage = ceil(($jumlah / $limit));
        }
        else
        {
            $jumPage = 1;
        }

        $nPage = $nextPage;
        $jumRec = $limit * $pagePerCols;
        
        if ($offset != 0)
            $hasil .= "<li class=\"previous\"><a class=\"paging\" " . "href=\"?os=0&np=1&cp=1" . $addLink . "&v=" . $var . " \">&laquo; First</a><li>";
        else
            $hasil .= "<li class=\"previous-off\">&laquo; First</li>";
        if ($nPage >= $pagePerCols && $nPage > 1)
            $hasil .= "<li class=\"previous\"><a class=\"paging\" " . "href=\"?os=" . (($pagePerCols * $limit * ($colPage - 1)) - $limit) . "&np=" . ($nPage - $pagePerCols) . "&cp=" . ($colPage - 1) . $addLink . " &v=" . $var . "\">&laquo; Previous</a><li>";
        
        if ($jumlah > $limit)
        {
            for ($i = 0; $i < $pagePerCols; $i++)
            {
                if ($jumlah > (($i + ($nPage - 1)) * $limit))
                {
                    $hasil .= "" . ($offset != ($i + ($nPage - 1)) * $limit ? "<li><a href=\"?os=" . (($i + ($nPage - 1)) * $limit) . "&np=" . $nPage . "&cp=" . $colPage . $addLink . " \">" . ($i + $nPage) . "</a></li>" : "<li class=\"active\">" . ($i + $nPage) . "</li>");
                }
            }
        }
        else
        {
            $hasil .= "<li class=\"active\">1</li>";
        }
        
        if ($pagePerCols * $colPage < $jumPage && $jumlah > $limit * $pagePerCols)
        {
            $hasil .= "<li class=\"next\"><a class=\"paging\" href=\"?" . $addLink . "&os=" . ($pagePerCols * $limit * ($colPage)) . "&np=" . ($nPage + $pagePerCols) . "&cp=" . ($colPage + 1) . "&v=" . $var . "\">Next &raquo;</a></li>";
        }

        if ($jumlah > $offset + $limit)
        {
            $hasil .= "<li class=\"next\"> ";
            $os = (($jumlah / $limit) > $jumPage ? ($jumPage * $limit) : ($jumPage - 1) * $limit);
            $hasil .= "<a class=\"paging\" href=\"?os= " . (($jumlah / $limit) > $jumPage ? ($jumPage * $limit) : ($jumPage - 1) * $limit) . "&np=" . $nPage . "&cp=" . $colPage . $addLink . "&v=" . $var . "\">Last &raquo;</a><li>";
        }
        else
        {
            $hasil .= "<li class=\"next-off\">Last &raquo;</li>";
        }

        if ($hasil != "")
        {
            $hasil = "<ul id=\"pagination-clean\">" . $hasil . "</ul>";
        }

        return $hasil;
    }

    function get_object($query)
    {
        $result = $this->db->query($query);

        if ($result->num_rows() > 0)
        {
            return $result->row();
        }
        else
        {
            return false;
        }
    }
    
    function get_scalar($query, $field_name)
    {
        $result = $this->db->query($query);

        if ($result->num_rows() > 0)
        {
            $row = $result->row();
            
            return $row->$field_name;
        }
        else
        {
            return false;
        }
    }
    
    
    

}

?>
